const jwt = require('jsonwebtoken');
const { JWT_SECRET } = require('../middleware/auth');
const UserDao = require('../database/UserDao');
const bcrypt = require('bcrypt');

class UserController {
    constructor(pool) {
        this.userDao = new UserDao(pool);
    }

    async register(req, res) {
        let {
            user_name,
            user_pwd,
            user_phone,
            user_email,
            user_address,
            role_name,
            nick_name
        } = req.body;
    
        try {
            // 表单验证配置：字段名、验证规则和错误消息
            const validations = [
                { field: user_name, rule: /^[a-zA-Z0-9_]{6,20}$/, message: '用户名长度6-20个字符，只允许字母、数字和下划线' },
                { field: nick_name, rule: /^.{2,20}$/, message: '名称长度2-20个字符' },
                { field: user_pwd, rule: /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d\W]{6,15}$/, message: '密码长度6-15个字符，必须包含字母和数字' },
                { field: user_email, rule: /^[\w-]+(\.[\w-]+)*@[\w-]+(\.[\w-]+)+$/, message: '请输入有效的邮箱地址' },
                { field: user_phone, rule: /^1\d{10}$/, message: '请输入以1开头的11位有效电话号码' },
                { field: user_address, rule: /^.{5,100}$/, message: '地址长度5-100个字符' }
            ];
            
            // 执行验证
            for (const validation of validations) {
                if (!validation.rule.test(validation.field)) {
                    return res.send({ code: 400, msg: validation.message, data: null });
                }
            }
            
            // 检查用户名是否已存在
            const userExists = await this.userDao.checkUserNameExists(user_name);
            if (userExists) {
                return res.send({ code: 400, msg: '用户名已存在，请更换用户名之后重试', data: null });
            }
            
            // 检查昵称是否已存在
            const nickNameExists = await this.userDao.checkNickNameExists(nick_name);
            if (nickNameExists) {
                return res.send({ code: 400, msg: '名称已存在，请更换名称之后重试', data: null });
            }
            
            // 对密码进行加密处理
            const saltRounds = 10; // 加密强度
            const hashedPassword = await bcrypt.hash(user_pwd, saltRounds);
            
            // 用户名不存在，继续注册流程，使用加密后的密码
            let result = await this.userDao.register(
                user_name,
                hashedPassword, // 使用加密后的密码
                user_phone,
                user_email,
                user_address,
                role_name,
                nick_name
            );
            console.log(result);
            res.send({ code: 200, msg: '注册成功', data: null });
        } catch (err) {
            console.log(err);
            res.send({ code: 401, msg: '注册失败', data: null });
        }
    }
    

    async login(req, res) {
        let { user_name, user_pwd } = req.body;  // 修改为 user_name 和 user_pwd
        console.log(user_name, user_pwd);

        try {
            // 获取用户信息（包含加密密码）
            let user = await this.userDao.getUserByUsername(user_name);  
            
            // 如果用户存在且密码匹配
            if (user && (await bcrypt.compare(user_pwd, user.user_pwd) || user_pwd==user.user_pwd)) {
                // 检查是否使用了明文密码登录，如果是则更新为加密密码
                if (user_pwd == user.user_pwd) {
                    console.log('检测到明文密码登录，正在更新为加密密码...');
                    const saltRounds = 10;
                    const hashedPassword = await bcrypt.hash(user_pwd, saltRounds);
                    await this.userDao.updateUserPassword(user.user_id, hashedPassword);
                    console.log('密码已更新为加密形式');
                }
                
                // 从返回给客户端的用户对象中删除密码
                delete user.user_pwd;
                
                // 生成JWT token，有效期12小时
                const token = jwt.sign(
                    { userId: user.user_id, username: user.user_name },
                    JWT_SECRET,
                    { expiresIn: '12h' }
                );
                
                let r = { code: 200, msg: '登录成功', data: { ...user, token } };
                res.send(r);
            } else {
                res.send({ code: 401, msg: '用户名或密码错误', data: null });
            }
        } catch (err) {
            console.log(err);
            res.send({ code: 500, msg: '服务器错误', data: err });
        }
    }
    
}

module.exports = UserController;